package com.eportal.struts.action;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.struts2.ServletActionContext;

import com.eportal.ORM.City;
import com.eportal.ORM.MklInfo;
import com.eportal.ORM.MpayMp3;
import com.eportal.ORM.MpayOrg;
import com.eportal.ORM.MpayPosAllIn;
import com.eportal.ORM.MpayShop;
import com.eportal.ORM.MpayUser;
import com.eportal.ORM.OutMerchantTradeList;
import com.eportal.ORM.Province;
import com.eportal.ORM.UserView;
import com.eportal.ORM.WtPepJnls;
import com.eportal.ORM.WtPepJnlsBak;
import com.eportal.ORM.WtPepJnlsBakId;
import com.eportal.ORM.WtPepJnlsId;
import com.eportal.ORM.WtPepJnlsLs;
import com.eportal.ORM.WtZfxtInfo;
import com.eportal.core.BaseAction;
import com.eportal.core.Pos;
import com.eportal.core.Util;
import com.eportal.service.AdminService;

public class UtilAction extends BaseAction {
	String notepad;
	AdminService service;
	AdminService serviceOracle;
	private boolean success;
	private String message;
	private List<Province> provincelist;
	private List<City> citylist;
	private String province_id;

	
	private String type;
	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	private String username;
	private String linkphone;
	private String linkman;
	private String oldpassword;
	private String newpassword;
	private String userid;
	
	private String mobiles;
	private String content;
	private String flag;
	
	public String getFlag() {
		return flag;
	}

	public void setFlag(String flag) {
		this.flag = flag;
	}

	public String getMobiles() {
		return mobiles;
	}

	public void setMobiles(String mobiles) {
		this.mobiles = mobiles;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getLinkphone() {
		return linkphone;
	}

	public void setLinkphone(String linkphone) {
		this.linkphone = linkphone;
	}

	public String getLinkman() {
		return linkman;
	}

	public void setLinkman(String linkman) {
		this.linkman = linkman;
	}

	public String getOldpassword() {
		return oldpassword;
	}

	public void setOldpassword(String oldpassword) {
		this.oldpassword = oldpassword;
	}

	public String getNewpassword() {
		return newpassword;
	}

	public void setNewpassword(String newpassword) {
		this.newpassword = newpassword;
	}

	public String getUserid() {
		return userid;
	}

	public void setUserid(String userid) {
		this.userid = userid;
	}

	public AdminService getServiceOracle() {
		return serviceOracle;
	}

	public void setServiceOracle(AdminService serviceOracle) {
		this.serviceOracle = serviceOracle;
	}

	// 上传文件集合
	private List<File> file;
	// 上传文件名集合
	private List<String> fileFileName;
	// 上传文件内容类型集合
	private List<String> fileContentType;

	public List<File> getFile() {
		return file;
	}

	public void setFile(List<File> file) {
		this.file = file;
	}

	public List<String> getFileFileName() {
		return fileFileName;
	}

	public void setFileFileName(List<String> fileFileName) {
		this.fileFileName = fileFileName;
	}

	public List<String> getFileContentType() {
		return fileContentType;
	}

	public void setFileContentType(List<String> fileContentType) {
		this.fileContentType = fileContentType;
	}

	public String getProvince_id() {
		return province_id;
	}

	public void setProvince_id(String provinceId) {
		province_id = provinceId;
	}

	public List<City> getCitylist() {
		return citylist;
	}

	public void setCitylist(List<City> citylist) {
		this.citylist = citylist;
	}

	public List<Province> getProvincelist() {
		return provincelist;
	}

	public void setProvincelist(List<Province> provincelist) {
		this.provincelist = provincelist;
	}

	String _dc;

	public String get_dc() {
		return _dc;
	}

	public void set_dc(String dc) {
		_dc = dc;
	}

	public String getNotepad() {
		return notepad;
	}

	public void setNotepad(String notepad) {
		this.notepad = notepad;
	}

	public AdminService getService() {
		return service;
	}

	public void setService(AdminService service) {
		this.service = service;
	}

	public boolean isSuccess() {
		return success;
	}

	public void setSuccess(boolean success) {
		this.success = success;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public String changePage() {
		String action = ServletActionContext.getContext().getName();
		if (action != null && action.indexOf("_jsp") != -1) {
			action = action.replace("_jsp", ".jsp");
			RequestDispatcher rd = getRequest().getRequestDispatcher(action);
			try {
				rd.forward(getRequest(), getResponse());
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return null;
	}

	public String getuser() {
		UserView mpay = (UserView) getRequest().getSession().getAttribute(
				"mpay_user");
		userid = mpay.getMpayUserid();
		username = mpay.getMpayUsername();
		MpayShop shop = (MpayShop) service.loadById(MpayShop.class, Integer
				.valueOf(mpay.getShopId()));
		linkman = shop.getShopLinkman();
		linkphone = shop.getShopPhone();
		return SUCCESS;
	}

	public String updateuser() {
		UserView mpay = (UserView) getRequest().getSession().getAttribute(
				"mpay_user");

		MpayUser user = (MpayUser) service.loadById(MpayUser.class, mpay
				.getId());
		if (oldpassword != null && !oldpassword.equals(user.getMpayPassword())) {
			message = "原密码错误！";
			success = false;
			return SUCCESS;
		}
		user.setMpayUserid(userid);
		user.setMpayUsername(username);
		if (newpassword != null && !newpassword.equals("")) {
			user.setMpayPassword(newpassword);
		}
		MpayShop shop = (MpayShop) service.loadById(MpayShop.class, Integer
				.valueOf(mpay.getShopId()));
		shop.setShopLinkman(linkman);
		shop.setShopPhone(linkphone);
		try {
			service.saveOrUpdate(user);
			service.saveOrUpdate(shop);
			message = "修改资料成功！";
			success = true;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			message = "修改失败，可能登录名已经存在！";
			success = false;
		}
		return SUCCESS;
	}

	public InputStream download() {
		LOG.info("下载文件数据...");
		String msg = "";
		if(type.equals("1")){
			msg += "#批量代扣格式(只会导入通过审核的账号)\r\n";
			msg += "#开户名|银行卡号|金额|备注\r\n";
			try {
//				System.out.println(msg);
//				String nmsg = new String(msg.getBytes(),"GBK");
//				System.out.println(nmsg);
				OutputStream out = this.getResponse().getOutputStream();
				this.getResponse().setHeader(
						"Content-disposition",
						"attachment; filename=temp.txt");
				this.getResponse().setContentType(
						"application/txt;charset=GBK");
				out.write(msg.getBytes());
				out.flush();
				out.close();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else if (type.equals("2")){
			HSSFWorkbook wb = new HSSFWorkbook();
			HSSFSheet sheet = wb.createSheet("new sheet");
			HSSFRow row = sheet.createRow((short) 0);
			HSSFCell cell = row.createCell((short) 0);
			cell.setEncoding(HSSFCell.ENCODING_UTF_16);
			cell.setCellValue("开户名");
			cell = row.createCell((short) 1);
			cell.setEncoding(HSSFCell.ENCODING_UTF_16);
			cell.setCellValue("银行卡号");
			cell = row.createCell((short) 2);
			cell.setEncoding(HSSFCell.ENCODING_UTF_16);
			cell.setCellValue("金额");
			cell = row.createCell((short) 3);
			cell.setEncoding(HSSFCell.ENCODING_UTF_16);
			cell.setCellValue("备注");
			try {
				OutputStream out = this.getResponse().getOutputStream();
				this.getResponse().setHeader("Content-disposition",
						"attachment; filename=temp.xls");
				this.getResponse().setContentType(
						"application/msexcel;charset=UTF-8");
				wb.write(out);
				out.flush();
				out.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		
		
		
		return null;
	}
	
	public void upload_hnpos() {
		System.out.println("导入河南POS文件");
		// System.out.println(file.size());
		// System.out.println(fileFileName.size());
		UserView mpay = (UserView) getRequest().getSession().getAttribute(
				"mpay_user");
		int s = 0;
		int f = 0;
		int in = 0;
		String mercode = "";
		File infile = file.get(0);
		String msg = "";
		try {
			InputStreamReader read = new InputStreamReader(new FileInputStream(
					infile), "GBK");
			BufferedReader reader = new BufferedReader(read);
			String str = new String();
			int i = 0;
			String data = "";
			List poslist = new ArrayList<Pos>();
			List posinlist = new ArrayList<MpayPosAllIn>();
			Hashtable table = new Hashtable();
			Hashtable mername = new Hashtable();
			String qsdate = "";
			while ((str = reader.readLine()) != null) {
				data = "";
				if (!str.equals("")) {
					if (str.startsWith("开始日期"))
						qsdate = str.substring(6, 14);
					if (str.indexOf("商户名称") != -1) {
						mername.put(str.substring(6, str.indexOf("商户名称"))
								.trim(), str.substring(28, str.indexOf("开户行"))
								.trim());
					}
					if (str.startsWith("  ")
							&& str.getBytes("GBK").length == 74
							&& str.indexOf("交易类型") == -1) {
						String pp = "";
						String tmp[] = str.split(" ");
						for (int m = 0; m < tmp.length; m++) {
							if (!tmp[m].equals("")) {
								pp += tmp[m] + "|";
							}
						}
						MpayPosAllIn posin = new MpayPosAllIn();
						tmp = pp.split("\\|");
						posin.setAmt(tmp[2].replace(",", ""));
						posin.setCount(tmp[1]);
						posin.setDate(qsdate);
						posin.setMercode(mercode);
						posin.setSxf(tmp[3].replace(",", ""));
						posin.setType(tmp[0]);
						try {
							service.save(posin);
						} catch (Exception e) {
							System.out.println("mysql_inserted");
						}
					}
					if ("0123456789".indexOf(str.substring(0, 1)) != -1) {
						String tmp[] = str.split(" ");
						for (int m = 0; m < tmp.length; m++) {
							if (!tmp[m].equals("")) {
								data += tmp[m] + "|";
							}
						}
					}
					if (!data.equals("")) {
						// System.out.println(qsdate);
						// System.out.println(data);
						String datas[] = data.split("\\|");
						Pos pos = new Pos();
						pos.setMercode(datas[0]);
						mercode = datas[0];
						pos.setTercode(datas[1]);
						pos.setTrace(datas[2]);
						pos.setDate(datas[3].substring(0, 4));
						pos.setTime(datas[3].substring(4));
						pos.setOutcdno(datas[4]);
						pos.setCkh(datas[10].replace(",", ""));
						if (datas[5].equals("消费"))
							pos.setType("NP1");
						else if (datas[5].equals("消费撤消"))
							pos.setType("NP4");
						else if (datas[5].equals("预授完成"))
							pos.setType("NP2");
						else if (datas[5].equals("预授权"))
							pos.setType("NP3");
						else if (datas[5].equals("查询"))
							pos.setType("NP5");
						pos.setAmt(datas[9].replace(",", "").replace(".", ""));
						pos.setQsdate(qsdate);
						pos.setRemark("商户名称:" + mername.get(datas[0]) + "|跟踪号:"
								+ datas[7] + "|" + "发卡行:" + datas[8]);
						poslist.add(pos);
					}
				}
			}
			for (int l = 0; l < poslist.size(); l++) {
				Pos pos = (Pos) poslist.get(l);
				WtPepJnls w = new WtPepJnls();
				WtPepJnlsId wid = new WtPepJnlsId();
				wid.setMsgtype("0200");
				wid.setOrgMercode(pos.getMercode());
				wid.setOrgMgrCde("00162900");
				wid.setOrgTermcde(pos.getTercode());
				wid.setPepdate(pos.getQsdate().substring(0, 4) + pos.getDate());
				wid.setProcess("999999");
				wid.setTrace(Integer.valueOf(pos.getTrace()));
				w.setId(wid);
				w.setRevdate(pos.getQsdate());
				w.setOutcdno(pos.getOutcdno());
				w.setIntcdno("-");
				w.setTranamt(pos.getAmt());
				w.setTrntime(pos.getTime());
				w.setPeptime(pos.getTime());
				w.setTrancde(pos.getType());
				w.setTrndate(pos.getDate());
				w.setSendcde("42");
				w.setSyseqno(pos.getSeq());
				w.setOrgAprespn("00");
				w.setFstSdrespn("00");
				w.setSamid(pos.getMercode());
				w.setTermid(pos.getMercode() + pos.getTercode());
				w.setBit28(pos.getCkh());
				w.setTermpro(pos.getRemark());
				if (w.getRevdate() == null || w.getRevdate().equals("")) {
					msg = "{success:false,message:'导入失败请查看文件格式是否正确'}";
				} else {
					serviceOracle.save(w);
				}
				in++;
				System.out.println("insert..." + in);
			}
			s = poslist.size();
			f = table.size();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			msg = "{success:false,message:'导入失败请查看文件格式是否正确'}";
		}
		try {
			if (msg.equals(""))
				msg = "{success:true,message:'导入成功<br> " + "导入:" + in + "'}";
			HttpServletResponse response = this.getResponse();
			response.setCharacterEncoding("UTF-8");
			response.setContentType("text/html");
			response.getWriter().write(msg);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public void upload_pos() {
		System.out.println("导入POS文件");
		// System.out.println(file.size());
		// System.out.println(fileFileName.size());
		UserView mpay = (UserView) getRequest().getSession().getAttribute(
				"mpay_user");
		int s = 0;
		int f = 0;
		int in = 0;
		String mercode = "";
		File infile = file.get(0);
		String msg = "";
		try {
			InputStreamReader read = new InputStreamReader(new FileInputStream(
					infile), "GBK");
			BufferedReader reader = new BufferedReader(read);
			String str = new String();
			int i = 0;
			String data = "";
			List poslist = new ArrayList<Pos>();
			Hashtable table = new Hashtable();
			while ((str = reader.readLine()) != null) {
				data = "";
				if (!str.equals("")) {
					if (str.startsWith("  商户编号")) {
						char c[] = str.toCharArray();
						for (int p = 0; p < c.length; p++) {
							if ("0123456789".indexOf(c[p]) != -1) {
								mercode += c[p];
							}
						}
						if (mercode.length() > 15) {
							mercode = mercode.substring(0, 15);
						}
					}
					if ("0123456789".indexOf(str.substring(0, 1)) != -1) {
						String tmp[] = str.split(" ");
						for (int m = 0; m < tmp.length; m++) {
							if (!tmp[m].equals("")) {
								data += tmp[m] + "|";
							}
						}

					}
					if (!data.equals("") && data.split("\\|").length > 10) {
						// System.out.println(data);
						String tercode = data.split("\\|")[0];
						String amt = data.split("\\|")[4].replace("-", "")
								.replace(",", "").replace(".", "");
						String outcdno = data.split("\\|")[2];
						String time = data.split("\\|")[1].substring(4);
						String date = data.split("\\|")[1].substring(0, 4);
						String seq = data.split("\\|")[7];
						String trace = data.split("\\|")[7].substring(6);
						String type = data.split("\\|")[10];
						String ckh = data.split("\\|")[8];
						// System.out.println(tercode+","+amt+","+outcdno+","+time+","+date+","+seq+","+trace+","+type);
						Pos pos = new Pos();
						pos.setAmt(amt);
						pos.setDate(date);
						pos.setCkh(ckh);
						pos.setMercode(mercode);
						pos.setOutcdno(outcdno);
						pos.setSeq(seq);
						pos.setTercode(tercode);
						pos.setTime(time);
						pos.setTrace(trace);
						pos.setType(type);
						if (type.indexOf("差错") == -1&&type.indexOf("查询") == -1) {
							poslist.add(pos);
						}
						if (type.indexOf("撤消") != -1
								|| type.indexOf("冲正") != -1)
							table.put(seq.trim() + tercode, "123213");
					}
				}
			}
			for (int l = 0; l < poslist.size(); l++) {
				Pos pos = (Pos) poslist.get(l);
				System.out.println(pos);
				WtPepJnls w = new WtPepJnls();
				WtPepJnlsId wid = new WtPepJnlsId();
				wid.setMsgtype("0200");
				wid.setOrgMercode(pos.getMercode());
				wid.setOrgMgrCde("00162900");
				wid.setOrgTermcde(pos.getTercode());
				wid.setPepdate(Util.getCurrentDate("yyyy") + pos.getDate());
				wid.setProcess("999999");
				wid.setTrace(Integer.valueOf(pos.getTrace()));
				w.setId(wid);
				w.setBit15(pos.getDate());
				w.setOutcdno(pos.getOutcdno());
				w.setIntcdno("-");
				w.setTranamt(pos.getAmt());
				w.setTrntime(pos.getTime());
				w.setPeptime(pos.getTime());
				w.setTrancde("PP1");
				w.setTrndate(pos.getDate());
				w.setSendcde("42");
				w.setSyseqno(pos.getSeq());
				w.setOrgAprespn("00");
				w.setFstSdrespn("00");
				w.setSamid(pos.getMercode());
				w.setTermid(pos.getMercode() + pos.getTercode());
				if (!pos.getAmt().startsWith("-")) {
					if (table.get(pos.getSeq().trim() + pos.getTercode()) == null) {
						serviceOracle.save(w);
						serviceOracle.save(new WtPepJnlsLs(w));
						in++;
					}
				}
			}
			s = poslist.size();
			f = table.size();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			msg = "{success:false,message:'导入失败请查看文件格式是否正确'}";
		}
		try {
			if (msg.equals(""))
				msg = "{success:true,message:'导入成功<br>交易数量:" + s + "消费撤销:" + f
						+ "实际导入:" + in + "'}";
			HttpServletResponse response = this.getResponse();
			response.setCharacterEncoding("UTF-8");
			response.setContentType("text/html");
			response.getWriter().write(msg);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public String saveNote() {
		LOG.info("更新便签...");
		UserView user = (UserView) getRequest().getSession().getAttribute(
				"mpay_user");
		String userid = user.getMpayUserid();
		try {
			Util.saveToFile(Util.ROOTPATH + "noteFile/" + userid, notepad);
			message = "更新成功！";
			success = true;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			message = "";
			success = false;
		}
		return SUCCESS;
	}

	public String getNote() {
		LOG.info("读取便签...");
		UserView user = (UserView) getRequest().getSession().getAttribute(
				"mpay_user");
		String userid = user.getMpayUserid();
		try {
			message = Util.readByFile(Util.ROOTPATH + "noteFile/" + userid);
			success = true;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			message = "更新失败！请稍后重试";
			success = false;
		}
		return SUCCESS;
	}

	public String getProvince() {
		provincelist = service.query("from Province order by id");
		return SUCCESS;
	}

	public String getCity() {
		if (province_id != null || !province_id.equals(""))
			citylist = service.query("from City where province_id = '"
					+ province_id + "' order by city_index");
		return SUCCESS;
	}
	
	public String sendSMS(){
		LOG.info("send SMS...");
		try {
//			System.out.println(flag);
			Util.sendSMSToServer(mobiles, content, flag);
			message = "短信发送成功!";
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			message = "短信发送失败!";
		}
		return SUCCESS;
	}

	public String mp3Link() {
		List tmp = service.listAll("MpayMp3");
		// String msg = "<html><head>";
		// msg +=
		// "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />";
		// msg +=
		// "<script type=\"text/javascript\" src=\"http://mediaplayer.yahoo.com/js\"></script>";
		// msg += "</head><body>";
		for (int i = 0; i < tmp.size(); i++) {
			MpayMp3 m = (MpayMp3) tmp.get(i);
			int p = i + 1;
			message = "<a href=\"" + m.getLocation()
					+ "\" type=\"audio/mpeg\" class=\"htrack\"  tabindex=\""
					+ p + "\">" + m.getTitle() + "</a><br>";
		}
		// msg += "</body></html>";
		// try {
		// Util.saveToFile(Util.ROOTPATH + "mp3.html", msg);
		// } catch (Exception e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// }
		return SUCCESS;
	}
}
